/*
 * @Description: 异步并行Promise钩子
 * @Author: wangqi
 * @Date: 2021-04-17 12:05:11
 * @LastEditTime: 2021-04-18 12:20:27
 */

class AsyncParallelHook {
    constructor(args) {
        this.hooks = [];
    }

    tapPromise(name, task) {
        this.hooks.push(task);
    }

    promise(...res) {
        let [first, ...others] = this.hooks;
        let ret = first(...res);
        return others.reduce((pre, curr) => {
            // 取promise的resolve, 进行下一次的钩子执行
            return pre.then((...args) => curr(...args))
        }, ret)
    }

}

let asyncparallelhook = new AsyncParallelHook(['name']);
asyncparallelhook.tapPromise('node', (name) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('node', name);
            resolve({ "sanme": "wq" });
        }, 1000);
    })
});

asyncparallelhook.tapPromise('vue', (name) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('vue', name)
            resolve("wangqi");
        }, 2000);
    })

});

asyncparallelhook.promise('wq').then(function () {
    console.log("end~~")
});


